package com.mo.xi.ge.info

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import com.mo.xi.ge.info.bean.DataNetWork
import com.mo.xi.ge.info.help.DataConstant
import com.mo.xi.ge.info.help.EntryInfoManager
import com.mo.xi.ge.info.help.checkAppPermission
import com.mo.xi.ge.info.loc.LocationWrapper

/**
 * date:2024/1/26
 **/
class DaleInfoInstance {

    companion object {

        @SuppressLint("StaticFieldLeak")
        internal val INSTANCE = DaleInfoInstance()

        fun get(context: Context): DaleInfoInstance {
            INSTANCE.mContext = context.applicationContext
            INSTANCE.startLocation()
            EntryInfoManager.mSource = context.packageName.replace(".", "_")
            return INSTANCE
        }
    }

    private constructor()

    internal var mGaidBack: (() -> String)? = null
    internal var mIpAddr: (() -> String)? = null

    internal var mContext: Context? = null
    internal var usrId: String? = null
    internal lateinit var host: String
    internal lateinit var key: String
    internal lateinit var secret: String
    internal lateinit var aes: String
    fun init(host: String, key: String, secret: String, aes: String) {
        this.host = host
        this.key = key
        this.secret = secret
        this.aes = aes
    }

    fun setUsrId(id: String) {
        usrId = id
    }

    fun setIpAddress(ipAddr: () -> String): DaleInfoInstance {
        this.mIpAddr = ipAddr
        return this
    }

    fun setEncrytInfo(publicKey: String, secrdid: String): DaleInfoInstance {
        DataConstant.mPublicKey = publicKey
        DataConstant.mSecretid = secrdid
        return this
    }

    fun createTokenKey(@DaleLoca action: String): String {
        if (DataConstant.mSecretid.isEmpty()) {
            throw IllegalArgumentException("The setCommonInfo method needs to be called first，parnetId not be null")
        }
        EntryInfoManager.mInfoTag = action
        mContext?.let { EntryInfoManager.reCreateToken(it) }
        return EntryInfoManager.mDataToken.orEmpty()
    }

    /**
     * 请求定位信息
     */
    fun startLocation() {
        val ctx = mContext ?: return
        if (ctx.checkAppPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) {
            LocationWrapper.create(ctx)
            LocationWrapper.getOnceLocationCallback { }
        }
    }

    fun getDalaToken() = EntryInfoManager.mDataToken

    // 上传信息
    fun dalaDevice() {
        DataNetWork.mRetryCount = 0
        DataNetWork.postInfo()
    }

    // 初始化
    fun dalaInit() {
        DataNetWork.postInfo(DataNetWork.TYPE1)
    }
}
